'use strict'
import io from 'socket.io-client'
import EventEmitter from './EventEmitter'
export default class Socket extends EventEmitter {
  constructor (platform, roomId) {
    super()
    this.state = 0
    this.roomId = roomId
    this.platform = platform
    this.isReconnect = false
    this.isInitRoom = false
    this.code = {
      connect: 0,
      connecting: 1,
      disconnect: 2,
      error: 3,
      reconnect: 4,
      reconnecting: 5,
      reconnect_error: 6,
      BIND: 7,
      SUCCESS: 8
    }
    this.socket = io.connect('http://danmu.yiceba.com/')
    this.init()
  }
  init () {
    this.socket.on('connect', this.onConnect.bind(this))
    this.socket.on('connecting', this.onConnecting.bind(this))
    this.socket.on('disconnect', this.onDisconnect.bind(this))
    this.socket.on('error', this.onError.bind(this))
    this.socket.on('reconnect', this.onReconnect.bind(this))
    this.socket.on('reconnecting', this.onReconnecting.bind(this))
    this.socket.on('reconnect_error', this.onReconnectError.bind(this))
    this.socket.on('roomUpdate', this.onRoomUpdate.bind(this))
    this.socket.on('chatMsg', this.onChatMsg.bind(this))
    this.socket.on('initRoom', this.onInitRoom.bind(this))
  }
  onConnect () {
    this._bindRoom(this.platform, this.roomId)
    this.emit('connect')
    this._changeState(this.code.connect)
  }
  onConnecting () {
    this._changeState(this.code.connecting)
  }
  onDisconnect () {
    this._changeState(this.code.disconnect)
  }
  onError () {
    this._changeState(this.code.error)
  }

  onReconnect () {
    this.isReconnect = true
    this._changeState(this.code.reconnect)
  }
  onReconnecting () {
    this._changeState(this.code.reconnecting)
  }
  onReconnectError () {
    this._changeState(this.code.reconnect_error)
  }
  onRoomUpdate (data) {
    if (this.isInitRoom) {
      this.emit('roomUpdate', data.info)
    }
  }
  onChatMsg (data) {
    if (this.isInitRoom) {
      this.emit('chatMsg', data.msg)
    }
  }
  onInitRoom (data) {
    this._changeState(this.code.SUCCESS)
    if (this.isReconnect) {
      return
    }
    this.isInitRoom = true
    this.emit('initRoom', data)
  }
  onChangeState (state) {
    this.emit('changeState', state)
  }
  _changeState (state) {
    this.state = state
    if (this.isInitRoom) {
      this.onChangeState(state)
    }
  }
  remove () {
    this.socket.disconnect()
  }
  _bindRoom (platform, roomId) {
    this._changeState(this.code.BIND)
    this.socket.emit('Binding', {
      roomId,
      platform
    })
  }
}
